package cn.scxy.bookcity.service.impl;

import cn.scxy.bookcity.ex.ServiceException;
import cn.scxy.bookcity.mapper.UserLoginMapper;
import cn.scxy.bookcity.mapper.UserMapper;
import cn.scxy.bookcity.pojo.dto.UserLoginDTO;
import cn.scxy.bookcity.service.IUserLoginService;
import cn.scxy.bookcity.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Service
@Slf4j
public class UserLoginService implements IUserLoginService {
    @Override
    public void addNew(UserLoginDTO userLoginDTO) {

    }
    @Autowired
    private UserLoginMapper mapper;
    @Override
    public int  userlogin(UserLoginDTO userLoginDTO, HttpServletResponse response, HttpSession session) {
        UserLoginDTO u = mapper.selectByUserPhone(userLoginDTO.getPhone());
        if (u!=null){
            if (u.getPassword().equals(userLoginDTO.getPassword())){
                if (userLoginDTO.isC()){
                    Cookie c1 = new Cookie("phone",userLoginDTO.getPhone());
                    Cookie c2 = new Cookie("password",userLoginDTO.getPassword());
                    c1.setMaxAge(60*5);
                    c2.setMaxAge(60*5);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                //把当前登录的用户对象保存到Session里面
                session.setAttribute("user",u);
                return 1;
            }
            throw new ServiceException(ServiceCode.ERR_SELECT,"密码错误");
        }
        throw new ServiceException(ServiceCode.ERR_SELECT,"用户名不存在");
    }
}
